package com.yx.fsysserver.file.controller;

import com.yx.fsysserver.common.result.JsonResult;
import com.yx.fsysserver.file.domain.FileInfo;
import com.yx.fsysserver.file.service.AliOssService;
import com.yx.fsysserver.file.service.FileService;
import com.yx.fsysserver.file.vo.UploadResult;
import com.yx.fsysserver.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * 阿里云oss存储
 * @author cuihao
 * @create 2018-05-30-14:44
 * 如有不懂，请看https://blog.csdn.net/haohao123nana/article/details/51305594
 */
@RestController
@RequestMapping("/aliOss")
public class AliOssController {
    private Logger log = LoggerFactory.getLogger(AliOssController.class);

    @Autowired
    private AliOssService aliOssService;
    @Autowired
    private FileService fileService;

    /**
     * 得到秘钥 (管理员目录flag=1,用户目录flag=2)
     * @param flag
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/ossgetKey")
    public JsonResult getKey(int flag,HttpServletRequest request, HttpServletResponse response) throws Exception {
        return aliOssService.getKey(flag,request,response);
    }

    /**
     * oss回调此方法，然后回应客户端
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/osscallBack")
    public void callBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String c_length=request.getHeader("content-length");
        int c_i=Integer.parseInt(c_length);
        //解析阿里回调服务器的接口数据
        String ossCallbackBody = aliOssService.GetPostBody(request.getInputStream(), c_i);
        //验证是否是阿里发起的回调
        boolean ret = aliOssService.VerifyOSSCallbackRequest(request, ossCallbackBody);
        if (ret)
        {
            //保存oss返回来的文件信息
            //ossCallbackBody={"bucket":"k12b","object":"userdir/mmm.jpg","mimeType":"image/png","size":75540}
            int size=0;
            String bucket="",object="",mimeType="",uuid="";
            JSONObject jsonObject = JsonUtil.getJSONObject(ossCallbackBody);
            try {
                bucket = jsonObject.getString("bucket");     // k12b
                object = jsonObject.getString("object");     // userdir/mmm.jpg
                mimeType = jsonObject.getString("mimeType"); // image/png
                size = jsonObject.getInt("size");            // 75540
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //保存文件信息到数据库
            FileInfo fileInfo = new FileInfo();
            //创建时间
            fileInfo.setCreatetime(new Date());
            //文件大小
            fileInfo.setSize(Long.valueOf(size));
            //获取纯文件名
            fileInfo.setName(object);
            //获取文件后缀
            fileInfo.setSuffix(mimeType);
            //生成随机文件名
            fileInfo.setUuid(uuid);
            //生成路径
            fileInfo.setPath("");
            this.fileService.insertSelective(fileInfo);

            //返回给OSS
            aliOssService.response(request, response, "{\"Status\":\"OK\"}", HttpServletResponse.SC_OK);
        }
        else
        {
            aliOssService.response(request, response, "{\"Status\":\"verdify not ok\"}", HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    /**
     * 下载阿里文件
     * @param key (形如 "admin/2016-05-03/40e07ea8-0cf2-436c-a3c6-bfd55aedf65c.mp4" )
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/ossdownload")
    public void download(String key,HttpServletRequest request, HttpServletResponse response) throws Exception {
        aliOssService.download(key,request,response);
    }
    /**
     * 在线播放阿里文件
     * @param key (形如 "admin/2016-05-03/40e07ea8-0cf2-436c-a3c6-bfd55aedf65c.mp4" )
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/ossplayOnline")
    public void playOnline(String key, HttpServletRequest request, HttpServletResponse response) throws Exception {
        aliOssService.playOnline(key,request,response);
    }

    /**
     * 批量删除阿里文件
     * @param keys
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/del", method = RequestMethod.DELETE)
    public JsonResult deleteBooks(@RequestParam(name = "keys") List<String> keys, HttpServletRequest request) throws Exception{
        aliOssService.del(keys);
        return new JsonResult(true, ("delete success"));
    }

    /**
     * vr，需要解压缩后存放 上传服务器并且上传阿里oss
     * @param multipartFile
     * author qyb
     * @return
     */
    @RequestMapping(value = "/uploadVr",method = RequestMethod.POST)
    public UploadResult uploadVrFile(@RequestParam("file") MultipartFile multipartFile){
        if (multipartFile == null) {
            return new UploadResult(false,"读取失败！",null,null,0,"","","");
        }
        InputStream inputStream = null;
        try {
            //获取文件名称
            String fileName = multipartFile.getOriginalFilename();
            inputStream = multipartFile.getInputStream();
            UploadResult result = this.fileService.uploadVrFile(inputStream,fileName);
            return result;
        } catch (IOException e) {
            log.error("",e);
        }
        return null;
    }


    /**
     * flash，需要解压缩后存放 上传服务器并且上传阿里oss
     * @param multipartFile
     * author qyb update by zml on 2018/10/16
     * @return
     */
    @RequestMapping(value = "/uploadFlash",method = RequestMethod.POST)
    public UploadResult uploadFlashFile(@RequestParam("file") MultipartFile multipartFile){
        if (multipartFile == null) {
            return new UploadResult(false,"读取失败！",null,null,0,"","","");
        }
        InputStream inputStream = null;
        try {
            //获取文件名称
            String fileName = multipartFile.getOriginalFilename();
            inputStream = multipartFile.getInputStream();
            UploadResult result = this.fileService.uploadFlashFile(inputStream,fileName);
            return result;
        } catch (IOException e) {
            log.error("",e);
        }
        return null;
    }

    /**
     * 清云数据添加资源时，点击保存或保存并提交
     * @param id
     * @param isCommit
     * @param localFilePath
     */
    @RequestMapping(value = "/asyncUpload", method = RequestMethod.GET)
    public void asyncUpload(@RequestParam("id") Long id,
                             @RequestParam(value = "isCommit") Integer isCommit,
                            @RequestParam(value = "url") String localFilePath){
        // 开启多线程执行上传文件至阿里云，上传完毕后，更新这里的数据
        System.out.println("异步上传文件到阿里云OSS...");
        fileService.asyncUpload(id, isCommit, localFilePath);
    }

}
